<?php
require_once __DIR__ . '/parameters.yml';

function getUrlForKline($ch)
{
    $HUOBI_KLINE = [
        '1min' => URL_HUOBI_KLINE_1MIN,
        '5min' => URL_HUOBI_KLINE_5MIN,
        '30min' => URL_HUOBI_KLINE_30MIN,
    ];

    $list = explode(".", $ch);
    $kline = end($list);
    if (isset($HUOBI_KLINE[$kline])) {
        return $HUOBI_KLINE[$kline];
    }
    return null;
}

function httpRequest($url, $json, $timeout = 5000)
{
    if (false === $curl = curl_init()) {
        throw new RuntimeException('Unable to create a cURL handle.');
    }

    $http_user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0';

    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json),

    ));

    curl_setopt($curl, CURLOPT_USERAGENT, $http_user_agent);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);

    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_MAXREDIRS, 3);

    $response = curl_exec($curl);

    if (false === $response) {
        $error = curl_error($curl);
        curl_close($curl);
        throw new RuntimeException(sprintf('An error occurred: %s.', $error));
    }

    $headersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headersSize);
    $body = substr($response, $headersSize);

    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if (400 == $statusCode) {
        throw new RuntimeException('400 error.');
    }

    if (200 != $statusCode) {
        throw new RuntimeException(sprintf('The web service failed for an unknown reason (HTTP %s).', $statusCode));
    }

    return array($headers, $body);
}
